package com.vr.xuecheng.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vr.xuecheng.auth.dto.AuthParamsDTO;
import com.vr.xuecheng.auth.dto.LoginUserDTO;
import com.vr.xuecheng.auth.entity.User;
import com.vr.xuecheng.auth.mapper.UserMapper;
import com.vr.xuecheng.auth.service.IAuthService;
import com.vr.xuecheng.base.exception.XueChengPlusException;
import com.vr.xuecheng.feign.client.CheckCodeClient;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author hzh
 * @date 2025/03/30
 * 密码模式的认证实现
 */
@Service("password_authService")
@RequiredArgsConstructor
public class PasswordAuthServiceImpl implements IAuthService {
    private final UserMapper userMapper;
    private final CheckCodeClient checkCodeClient;
    private final PasswordEncoder bCryptPasswordEncoder;
    @Override
    public LoginUserDTO execute(AuthParamsDTO authParamsDTO) {
        // 校验验证码
        String checkcodekey = authParamsDTO.getCheckcodekey();
        String checkcode = authParamsDTO.getCheckcode();
        if (StrUtil.isBlank(checkcodekey) || StrUtil.isBlank(checkcode)) {
            XueChengPlusException.cast("请输入验证码");
        }
        // 远程调用验证码服务校验验证码是否正确
        boolean is = checkCodeClient.verify(checkcodekey, checkcode);
        if (!is) {
            XueChengPlusException.cast("验证码错误");
        }
        // 查询数据库
        User userOfLogin = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, authParamsDTO.getUsername()));
        if (userOfLogin == null) {
            // 为空时表示用户不存在
            XueChengPlusException.cast("用户不存在");
        }
        // 校验密码，这里可以省略DaoAuthenticationProvider帮你做了
        String password = authParamsDTO.getPassword();
        boolean isPassword = bCryptPasswordEncoder.matches(password, userOfLogin.getPassword());
        if (!isPassword) {
            XueChengPlusException.cast("密码错误");
        }
        return BeanUtil.copyProperties(userOfLogin, LoginUserDTO.class);
    }
}
